﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Drawing;

namespace curbside.Web.httpHandlers
{
    /// <summary>
    /// 生成验证码
    /// </summary>
    public class VerifyCode : IHttpHandler, IRequiresSessionState
    {
        HttpResponse response = null;
        HttpSessionState sessionState = null;

        #region IHttpHandler 成员

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            response = context.Response;
            sessionState = context.Session;
            this.GenImg(this.GenCode(4));
        }

        #endregion

        //产生随机字符串
        private string GenCode(int num)
        {
            string[] source ={"0","1","2","3","4","5","6","7","8","9",
                                "A","B","C","D","E","F","G","H","I","J","K","L","M","N",
                                "O","P","Q","R","S","T","U","V","W","X","Y","Z"};
            string code = "";
            Random rd = new Random();
            for (int i = 0; i < num; i++)
            {
                code += source[rd.Next(0, source.Length)];
            }
            return code;
        }

        //生成图片
        private void GenImg(string code)
        {
            using (Bitmap myPalette = new Bitmap(60, 20))
            {
                using (Graphics gh = Graphics.FromImage(myPalette))
                {
                    Rectangle rc = new Rectangle(0, 0, 60, 20);//定义一个矩形
                    gh.FillRectangle(new SolidBrush(Color.Silver), rc);//填充矩形
                    gh.DrawString(code, new Font("宋体", 16), new SolidBrush(Color.Gray), rc);//在矩形内画出字符串
                    myPalette.Save(response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//将图片显示出来
                    sessionState["VerifyCode"] = code;//将字符串保存到Session中，以便需要时进行验证
                }
            }
        }
    }
}